import json

import pymysql
from django_redis import get_redis_connection


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """

    menu = permission_session(user)  # 存储权限列表到redis中
    data = {
        'token': token,
        'id': user.id,
        'username': user.username,
        'menu': menu
    }

    return data



"""良宝utils"""
def permission_session(user):

    if user.is_superuser:

        # 打开数据库连接
        db = pymysql.connect("127.0.0.1", "root", "mysql", "vnemy")
        # 使用 cursor() 方法创建一个游标对象 cursor
        cursor = db.cursor()
        # 编写sql语句
        sql = f"select * from tb_menus"
        # sql = f"select * from tb_menus where parent_id=8"
        # sql = f"select * from tb_menus where parent_id=9"


        # 使用 execute()  方法执行 SQL 查询
        cursor.execute(sql)
        # 获取结果集中剩下的所有行
        data = cursor.fetchall()

        # 关闭数据库连接
        db.close()
        # menu = menu_list(data)
        # menu_list_json = json.dumps(menu_list(data))
        menu = []
        for i in data:
            menu.append(i[1])
        return menu




    user_id = user.id

    # 打开数据库连接
    db = pymysql.connect("127.0.0.1", "root", "mysql", "vnemy")
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()
    # 编写sql语句
    sql = f"select * from tb_permissions where id in (select distinct permission_id from tb_roles_permissions where role_id in (select role_id from tb_users_roles where user_id={user_id}))"
    # 使用 execute()  方法执行 SQL 查询
    cursor.execute(sql)
    # 获取结果集中剩下的所有行
    data = cursor.fetchall()

    # 关闭数据库连接
    db.close()
    #权限列表
    permission_list = []

    for i in data:
        permission_list.append(i[1]+'&'+i[2])

    permission_list_json = json.dumps(permission_list)

    redis_conn = get_redis_connection("permissions")
    redis_conn.set(user_id, permission_list_json)

    # 打开数据库连接
    db = pymysql.connect("127.0.0.1", "root", "mysql", "vnemy")
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()
    # 编写sql语句
    sql = f"select * from tb_menus where id in (select distinct menu_id from tb_roles_menus where role_id in (select role_id from tb_users_roles where user_id={user_id}))"
    # sql = f"select * from tb_menus where parent_id=8"
    # sql = f"select * from tb_menus where parent_id=9"

    # 使用 execute()  方法执行 SQL 查询
    cursor.execute(sql)
    # 获取结果集中剩下的所有行
    data = cursor.fetchall()

    # 关闭数据库连接
    db.close()
    # menu = menu_list(data)
    # menu_list_json = json.dumps(menu_list(data))
    menu = []
    for i in data:
        menu.append(i[1])
    return menu





# from django.contrib.auth.backends import ModelBackend
#
# from users.models import User
#
#
# def get_user_by_account(account):
#     """
#     根据帐号获取user对象
#     :param account: 账号，可以是用户名，也可以是手机号
#     :return: User对象 或者 None
#     """
#     try:
#
#         # 帐号为用户名
#         user = User.objects.get(username=account)
#     except User.DoesNotExist:
#         return None
#     else:
#         return user
#
#
# class UsernameMobileAuthBackend(ModelBackend):
#     """
#     自定义用户名或手机号认证
#     """
#
#     def authenticate(self, request, username=None, password=None, **kwargs):
#         user = get_user_by_account(username)
#         if user is not None and user.check_password(password):
#             return user